package com.iot.ig.websocket.config;

import com.iot.ig.websocket.handler.IotWebSocketHandler;
import com.iot.ig.websocket.interceptor.HandshakeInterceptorImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final IotWebSocketHandler iotWebSocketHandler;
    private final HandshakeInterceptorImpl handshakeInterceptor;

    public WebSocketConfig(HandshakeInterceptorImpl handshakeInterceptor,
                           IotWebSocketHandler iotWebSocketHandler) {
        this.handshakeInterceptor = handshakeInterceptor;
        this.iotWebSocketHandler = iotWebSocketHandler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                .addHandler(iotWebSocketHandler, "/ws/{username}")
                .setAllowedOrigins("*").addInterceptors(handshakeInterceptor);
    }
}
